//
//  AddSearchController.m
//  PropertyMananger
//
//  Created by bh on 17/2/13.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "AddSearchController.h"
#import "AddSearchCell.h"
#import "AddSearchView.h"
#import "AddEquipmentController.h"
#import "EquipmentQueryModel.h"

@interface AddSearchController ()
@property (nonatomic,strong) UILabel * nameLabel;

@property (nonatomic,strong) AddSearchView * addSearchView;
@property (nonatomic,strong) NSMutableArray * addSearchArray;

@end

@implementation AddSearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTitleViewName:@"新增"];
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 50, BHscreenW, BHscreenH - 64 - 50) isGroup:NO];
    self.tableView.separatorStyle = NO;
    self.tableView.backgroundColor = BHGrayColor;
    
    self.addSearchArray = [[NSMutableArray alloc]init];
    
    [self setupSearchBar];
    
    [self createPlaceHolder];
    
    [self createRefresh];
    
    [self postEquipmentQueryData];

}
#pragma mark - 创建刷新UI
- (void)createRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.nextPage = 1;
        
        self.isDown = YES;
        //获取数据
        [self postEquipmentQueryData];
        
    }];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.nextPage += 1;
        
        self.isDown = NO;
        //获取数据
        [self postEquipmentQueryData];
        
        //    [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}

#pragma mark - 搜索框
- (void)setupSearchBar
{
    self.nameLabel = [[UILabel alloc]init];
    [self.view addSubview:self.nameLabel];
    self.nameLabel.font = BHFont(15);
    self.nameLabel.textAlignment = NSTextAlignmentLeft;
    self.nameLabel.textColor = BHColor(102, 102, 102);
    self.nameLabel.text = @"设备编号:";
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).with.offset(15);
        make.top.equalTo(self.view).with.offset(7.5);
        make.size.mas_equalTo(CGSizeMake(75, 30));
    }];
    
    self.searchBar = [[MCSearchBar alloc] initWithFrame:CGRectMake(90, 10, BHscreenW - 100, 30) placeholder:nil];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入设备名称";
    self.searchBar.barTintColor = BHColor(237, 237, 237);
    [self.view addSubview:self.searchBar];
    [self.searchBar setBackgroundColor:BHColor(237, 237, 237)];
    self.searchBar.layer.cornerRadius = 15.0f;
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.borderWidth = 0.5;
    self.searchBar.layer.borderColor = BHColor(237, 237, 237).CGColor;
    self.searchBar.backgroundColor = BHColor(237, 237, 237);
    self.searchText = @"";
    
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.isSearch) {
        
        return self.resultArr.count;
    }else{
        
        return self.addSearchArray.count;
    }
    
    return 0;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddSearchCell * cell = [AddSearchCell cellWithTableView:tableView];
    EquipmentQueryModel * model = self.addSearchArray[indexPath.section];
    cell.equipmentCodeLabel.text = [NSString stringWithFormat:@"设备编号: %@",model.EquipmentNumber];
    cell.equipmentNameLabel.text = model.EquipmentName;
    cell.equipmentTypeLabel.text = model.SpecificationModel;
    cell.equipmentInstallLabel.text = model.InstallationAddress;
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
    EquipmentQueryModel * model = self.addSearchArray[indexPath.section];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedEquipment:equipmentCategory:equipmentName:EquipmentId:)]) {
        
        [self.delegate didSelectedEquipment:model.EquipmentNumber equipmentCategory:model.SpecificationModel equipmentName:model.EquipmentName EquipmentId:model.EquipmentId];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 170;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 15;
    
}
#pragma mark - 搜索框代理方法
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if (range.location == 0) {
        
        [self.resultArr removeAllObjects];
        [self.tableView reloadData];
        
//        self.placehoderImg.hidden = NO;
//        self.placehoderImg.hidden = NO;
    }
    return YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if (searchText.length == 0) {
        self.searchText = @"";
        self.isSearch = NO;
        
        [self.addSearchArray removeAllObjects];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header beginRefreshing];
        
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
    }
//    else{
//        [self.tableView.mj_header beginRefreshing];
//    }
    
    self.searchStr = searchText;
    [self.resultArr removeAllObjects];
    [self.addSearchArray removeAllObjects];
    
     [self.tableView reloadData];
    
    
    for (EquipmentQueryModel * model in self.addSearchArray) {
        if ([model.EquipmentName rangeOfString:searchText].location != NSNotFound) {
            [self.resultArr addObject:model.EquipmentName];
        }
        
    }
    
    if (self.resultArr.count != 0) {
        self.isSearch = YES;
        self.placehoderImg.hidden = YES;
        self.titleLabel.hidden = YES;
        [self.tableView reloadData];
    }
    
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    self.isDown = YES;
    [self postEquipmentQueryData];
    
    [self.tableView.mj_header beginRefreshing];
    
    [self.view endEditing:YES];
    
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
//    [self postEquipmentQueryData];
    
    [self.searchBar resignFirstResponder];
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    self.isDown = YES;
    self.nextPage = 1;
    
    [self postEquipmentQueryData];
    
    self.isSearch = NO;
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    [self.tableView endEditing:YES];
    self.isSearch = NO;
    
}

#pragma mark - 数据请求
- (void)postEquipmentQueryData{
    
    NSDictionary * parms = nil;
    if (self.searchStr != nil) {
        
        parms =  @{
                   @"Cid":userModel.CommunityID,
                   @"EquipmentName":self.searchStr,
                   @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                   @"json":@"\{\"jsonEntity\":\{},\"action\":\"findequipment\",\"version\":\"V1.0\"}"
                   };
        
    }else{
        
        parms =  @{
                   @"Cid":userModel.CommunityID,
                   @"EquipmentName":@"",
                   @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                   @"json":@"\{\"jsonEntity\":\{},\"action\":\"findequipment\",\"version\":\"V1.0\"}"
                   };
        
    }
    
    DLog(@"提交的参数 === %@",parms);
    
    [HomeNetWorkRequest postEquipmentQuerySuccess:^(id data) {
        
        if (self.isDown == YES) {
            
            [self.addSearchArray removeAllObjects];
            self.isDown = NO;
        }
        
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        //   DLog(@"%@",dict);
        DLog(@"返回 === %@",dict[@"Code"]);
        DLog(@"返回提示 === %@",dict[@"Msg"]);
        DLog(@"设备查询数据 == %@",array);
        
        for (NSDictionary * dict in array) {
            
            EquipmentQueryModel * model = [[EquipmentQueryModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.addSearchArray addObject:model];
        }
        if (self.addSearchArray != 0){
            
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
            
        }else{
            
          //  self.tableView.mj_footer.hidden = YES;
            
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }
        
//        if (self.addSearchArray.count <= 3) {
//            
//            self.tableView.mj_footer.hidden = YES;
//        }

        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [self.tableView reloadData];
        
    } Fail:^(NSString *errorDes) {

        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } param:parms ];
    
}
#pragma mark - 暂未图
- (void)createPlaceHolder
{
    
    self.placehoderImg = [[UIImageView alloc]init];
    [self.tableView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_query_no"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.tableView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无查询内容";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
